package animix.blue.server.user.service.impl;


import animix.blue.server.common.bean.pojo.Result;
import animix.blue.server.common.bean.model.User;
import animix.blue.server.common.bean.model.UserRole;
import animix.blue.server.user.mapper.UserMapper;
import animix.blue.server.user.mapper.UserRoleMapper;
import animix.blue.server.user.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Result getRoleIdsByUserId(Integer userId) {
        // id验证
        Result result = getUserById(userId);
        if (result.getCode() != 200) {
            return result;
        }
        // 查询
        List<UserRole> userRoleList = userRoleMapper.listByUserId(userId);
        // 组织返回数组
        if (userRoleList != null && userRoleList.size() > 0) {
            Integer[] roleIds = new Integer[userRoleList.size()];
            roleIds = userRoleList.stream().map(UserRole::getRoleId).toArray(Integer[]::new);
            return Result.ok(roleIds);
        } else {
            return Result.ok(new Integer[]{});
        }
    }

    @Transactional
    @Override
    public Result setByUserId(Integer userId, Integer[] roleIds) {
        // id验证
        Result result = getUserById(userId);
        if (result.getCode() != 200) {
            return result;
        }
        // 删除
        userRoleMapper.deleteByUserId(userId);
        // 插入
        if (roleIds != null && roleIds.length > 0) {
            List<UserRole> userRoleList = new ArrayList<>();
            for (int i = 0; i < roleIds.length; i++) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleIds[i]);
                userRole.setCreated(new Date());
                userRole.setUpdated(new Date());
                userRoleList.add(userRole);
            }
            userRoleMapper.insertBatch(userRoleList);
        }
        return Result.ok();
    }

    private Result getUserById(Integer id) {
        if (id != null) {
            User user = userMapper.getById(id);
            if (user != null) {
                return Result.ok(user);
            } else {
                return Result.build(400, "id不存在！");
            }
        } else {
            return Result.build(400, "id无效！");
        }
    }
}
